<script setup lang="ts">
import * as _ from 'lodash'
import Gallery from './gallery.vue'
import { ref, defineProps, nextTick, reactive } from 'vue'
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { getExampleById, switchStatus } from '@/api/example.ts'
import Title from '@/pages/detail/title.vue'
import Info from '@/pages/detail/info.vue'
import Relatives from '@/pages/detail/relatives.vue'
import { TitleType } from '@/pages/detail/type.ts'
import { shareUtils } from '@/utils/share'
const item = ref('')
const loading = ref(true)
const titleType = ref(TitleType.case)
const props = defineProps({
  id: String
})

onLoad(() => {
  getExampleById(props.id)
    .then((r) => {
      item.value = r
    })
    .finally(() => {
      nextTick(() => {
        loading.value = false
      })
    })


  const page = getCurrentPages().pop()

  let route = ''
  if (page.$page) {
    route = page?.$page?.fullPath
  } else {
    route = page.route
  }
  let path: string = shareUtils.buildPathQuery(route)
  onShareTimeline(() => {
    return {
      title: item.value.title,
      imageUrl: item.value.image,
      path
    }
  })
  onShareAppMessage(() => {
    return {
      title: item.value.title,
      imageUrl: item.value.image,
      path
    }
  })


})


const handleDoCollectFromChild = _.debounce((item) => {
  // todo 代优化
  if (item.is_collected) {
    switchStatus(item.id, 0).then((r) => {
      item.is_collected = false
    })
  } else {
    switchStatus(item.id, 1).then((r) => {
      item.is_collected = true
    })
  }
}, 500)
</script>

<template>
  <ForOneHeader :enableBack="true" />
  <view class="detail-container" v-if="item">
    <up-image :src="item.image" width="100%" height="100%" mode="widthFix" :showMenuByLongpress="false"></up-image>
    <MidLayout>
      <Title class="item" :type="titleType" @do-collect="handleDoCollectFromChild(item)" :item="item" />
    </MidLayout>
    <div class="gap"></div>
    <MidLayout class="info-layout">
      <Info class="info" :infoArray="[{ label: '品类', value: item.style }]" />
    </MidLayout>
    <div class="gap"></div>
    <view v-if="item.include_goods.length > 0">
      <MidLayout>
        <Relatives :relatives="item.include_goods" zh="使用花色" icon-name="more" :showb="false" />
      </MidLayout>
      <div class="gap"></div>
    </view>

    <MidLayout>
      <Gallery :arr="item.gallery" :loading="loading" />
    </MidLayout>
  </view>
  <u-loading-page :loading="loading"></u-loading-page>
</template>

<style lang="scss" scoped>
$little-legnth: 10rpx;

.detail-container {
  background-color: #f3f4f6;

  .info-layout {
    margin-top: $little-legnth;
  }
}

.pad {
  height: 30rpx;
}
</style>
